package com.surelution.projects.gard.controller

import java.text.SimpleDateFormat;

import com.surelution.projects.gard.core.DepartmentDailyPatrolVo;
import com.surelution.projects.gard.domain.Department;
import com.surelution.projects.gard.domain.Patrol;
import com.surelution.projects.gard.domain.PatrolClock;
import com.surelution.projects.gard.domain.PatrolRawRecord;
import com.surelution.projects.gard.domain.Poi;

class TourRawInfoGateController {

    def index = { }
	
	def tourPost = {
		ArrayList savedRawRecord = new ArrayList()
		ArrayList<Patrol> patrols = new ArrayList<Patrol>()
		
		String deptId = params.deptId
		String rawRecord = params.record
		String employeeId = params.employeeId
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		
		
		rawRecord.splitEachLine("\n") {line ->
			//line is a list, why?
			String[] words = line.get(0).split(",")
			if(words.length == 3) {
				String poiMacSn = words[0]
				String patrolTime = words[1]
				String tourDeviceSn = words[2]
				
				PatrolRawRecord record = new PatrolRawRecord(poiMacSn:poiMacSn, patrolTime:sdf.parse(patrolTime),tourDeviceSn:tourDeviceSn)
				record.save(flush:true)
				
				//save it to the list to process
				savedRawRecord.add(record)
			}
		}
		
		if(savedRawRecord.size() > 0) {
			savedRawRecord.each {record ->
				println record.id
				println record.poiMacSn
				println record.patrolTime
				println record.tourDeviceSn
				
				PatrolClock clock = process(record.patrolTime)
				println record.poiMacSn
				Poi poi = Poi.findByPoiMacSn(record.poiMacSn)
				println poi
				println clock
				println record
				if(clock && poi) {
					Patrol p = new Patrol(poi:poi, clock:clock,rawRecord:record)
					p.save(flush:true)
					patrols.add(p);
				}
			}
		}
		
		render(contentType:"text/xml") {
			tour {
				 Department(id:deptId)
				 Employee(id:employeeId)
				 if(patrols) {
					 Patrols() {
						 patrols.each {patrol ->
							 Patrol(id:patrol.id, address:patrol.poi.name, time:patrol.rawRecord.patrolTime, clock:patrol.clock.title)
						 }
					 }
				 }
			}
		}
	}
	
	def unnormalReport = {
		
		String sdate = params.date
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
		def date = sdf.parse(sdate)
		
		def depts = Department.list()
		def patrols = Patrol.findAllByPatrolTime(date, date + 1)
		depts.each {dept ->
			DepartmentDailyPatrolVo vo = new DepartmentDailyPatrolVo(dept, PatrolClock.list())
			
		}
	}
	
	private PatrolClock process(Date date) {
		def ret = null
		List<PatrolClock> clocks = PatrolClock.list()
		println clocks.size()
		println date
		clocks.each {clock ->
			println clock
			if(clock.isValid(date)) {
				println "get it:" + clock
				ret = clock
				return
			}
		}
		return ret;
	}
}
